package com.itcc.controller;

import com.itcc.utils.Constants;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.lang.reflect.Method;


public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodStr = req.getParameter(Constants.TAG);

        //method没有值就跳转到首页
        if (methodStr == null && methodStr.equals("")){
            methodStr=Constants.INDEX;
        }

        Class aClass = this.getClass();
        try {
            Method method=aClass.getMethod(methodStr,HttpServletRequest.class,HttpServletResponse.class);
            Object result=method.invoke(this,req,resp);

            if(result!=null){
                String str=(String) result;
                //转发:forward
                if(str.startsWith(Constants.FORWARD)){
                    String path=str.substring(str.indexOf(Constants.FLAG)+1);
                    req.getRequestDispatcher(path).forward(req,resp);
                }
                //重定向：redirect
                else if(str.startsWith(Constants.REDIRECT)){
                    String path=str.substring(str.indexOf(Constants.FLAG)+1);
                    resp.sendRedirect(path);

                }
                else{
                    resp.getWriter().println(str);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("exception", e);
            req.getRequestDispatcher("/message.jsp").forward(req,resp);
        }
    }
    public String index(HttpServletRequest req,HttpServletResponse resp) {
        return Constants.FORWARD+"/index.jsp";
    }

}
